﻿using System;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Text;
using System.Web;
using Framework;

namespace Enterprise
{
    public class ProductCategoryService : BaseService
    {
        /// <summary>
        /// 获取列表
        /// </summary>
        /// <returns></returns>
        public Table GetTable()
        {
            var table = new Table
            {
                Rows = DbHelperOleDb.Query("select * from tbproductcategory order by cosort desc").Tables["ds"].Rows,
                Total = DbHelperOleDb.GetSingle("select count(*) from tbproductcategory").SafeToInt()
            };
            return table;
        }

        /// <summary>
        /// 获取表格
        /// </summary>
        /// <returns></returns>
        public DataTable GetDataTable()
        {
            return DbHelperOleDb.Query("select * from tbproductcategory order by cosort desc").Tables["ds"];
        }



        /// <summary>
        /// 根据ID获取一条记录
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public DataRow GetById(int id)
        {
            return DbHelperOleDb.Query("select A.CoName,A.CoParentId,A.CoNormalImage,A.CoSmallImage,A.CoBigImage,A.CoNameEn,A.CoproductCategoryId,A.CoSort,B.CoName as CoParentName  from tbproductcategory as A left join tbproductcategory as B on A.CoParentId=B.CoproductCategoryId where A.CoproductCategoryId={0}".FormatWith(id)).Tables["ds"].Rows[0];
        }

        /// <summary>
        /// 添加产品分类
        /// </summary>
        /// <param name="name">分类名称</param>
        /// <param name="nameEn"> </param>
        /// <param name="parentId">父级ID</param>
        /// <param name="sort">排序</param>
        /// <param name="filedata"> </param>
        public int Add(string name, string nameEn, int parentId, int sort, HttpPostedFileBase filedata = null)
        {
            Check.Argument.IsNotOutOfLength(name, 2, 50, "分类名称");
            Check.Argument.IsNotOutOfLength(nameEn,  50, "分类名称(En)");
            var fileName = string.Empty;
            var thumFileName = string.Empty;
            if (filedata != null && filedata.ContentLength > 0)
            {
                var uploadHelper = new UploadHelper
                                       {
                                           PostedFile = filedata,
                                           RelativePath = ProductCategoryConfig.RelativePath,
                                           IsAdaptive = ProductCategoryConfig.IsAdaptive,
                                           IsImage = true,
                                           IsGenerateThumbnail = ProductCategoryConfig.IsGenerateThumbnail,
                                           FileMaxLength = ProductCategoryConfig.ImageSize,
                                           ThumbnailHeight = ProductCategoryConfig.ThumbnailHeight,
                                           ThumbnailWidth = ProductCategoryConfig.ThumbnailWidth,
                                           ThumbnailPrefix = ProductCategoryConfig.ThumbnailPrefix
                                       };
                if (!uploadHelper.Save())
                {
                    throw new Exception(uploadHelper.ErrorMessage);
                }
                fileName = uploadHelper.FileName;
                thumFileName = uploadHelper.ThumbnailFileName;
            }
            var strSql = new StringBuilder();
            strSql.Append("insert into tbproductcategory(");
            strSql.Append("CoName,CoNameEn,CoCategoryPath,CoParentId,CoDepth,CoType,CoLanguage,CoSort,CoNormalImage,CoSmallImage,CoBigImage");
            strSql.Append(")");
            strSql.Append(" values (");
            strSql.Append("@CoName,@CoNameEn,@CoCategoryPath,@CoParentId,@CoDepth,@CoType,@CoLanguage,@CoSort,@CoNormalImage,@CoSmallImage,@CoBigImage");
            strSql.Append(")");
            OleDbParameter[] parameters =
                {
                    new OleDbParameter("@CoName", OleDbType.VarChar, 255),
                    new OleDbParameter("@CoNameEn", OleDbType.VarChar, 255),
                    new OleDbParameter("@CoCategoryPath", OleDbType.LongVarWChar),
                    new OleDbParameter("@CoParentId", OleDbType.Integer),
                    new OleDbParameter("@CoDepth", OleDbType.Integer),
                    new OleDbParameter("@CoType", OleDbType.Integer),
                    new OleDbParameter("@CoLanguage", OleDbType.VarChar, 10),
                    new OleDbParameter("@CoSort", OleDbType.Integer),
                    new OleDbParameter("@CoNormalImage", OleDbType.VarChar, 255),
                    new OleDbParameter("@CoSmallImage", OleDbType.VarChar, 255),
                    new OleDbParameter("@CoBigImage", OleDbType.VarChar, 255)
                };
            parameters[0].Value = name;
            parameters[1].Value = nameEn;
            using (var sdr = DbHelperOleDb.ExecuteReader("select * from tbproductcategory where CoproductCategoryId={0}".FormatWith(parentId)))
            {

                if (sdr.Read())
                {
                    var depth = sdr["CoDepth"].SafeToInt() + 1;
                    if (ProductCategoryConfig.Depth < depth)
                    {
                        throw new Exception("分类深度不能超过{0}级!".FormatWith(ProductCategoryConfig.Depth));
                    }
                    parameters[2].Value = sdr["CoCategoryPath"].SafeToString() + parentId + ",";
                    parameters[3].Value = parentId;
                    parameters[4].Value = depth;

                }
                else
                {
                    parameters[2].Value = "";
                    parameters[3].Value = DBNull.Value;
                    parameters[4].Value = 1;
                }
            }
            parameters[5].Value = 0;
            parameters[6].Value = DBNull.Value;
            parameters[7].Value = sort;
            parameters[8].Value = fileName;
            parameters[9].Value = thumFileName;
            parameters[10].Value = fileName;
            var obj = DbHelperOleDb.Add(strSql.ToString(), parameters).SafeToInt();
            return obj;

        }
        public void Edit(int id, string name, string nameEn, int sort, HttpPostedFileBase filedata = null)
        {
            Check.Argument.IsNotOutOfLength(name, 2, 50, "分类名称");
            Check.Argument.IsNotOutOfLength(nameEn,  50, "分类名称(En)");
            var fileName = string.Empty;
            var thumFileName = string.Empty;
            if (filedata != null && filedata.ContentLength > 0)
            {
                var uploadHelper = new UploadHelper
                {
                    PostedFile = filedata,
                    RelativePath = ProductCategoryConfig.RelativePath,
                    IsAdaptive = ProductCategoryConfig.IsAdaptive,
                    IsImage = true,
                    IsGenerateThumbnail = ProductCategoryConfig.IsGenerateThumbnail,
                    FileMaxLength = ProductCategoryConfig.ImageSize,
                    ThumbnailHeight = ProductCategoryConfig.ThumbnailHeight,
                    ThumbnailWidth = ProductCategoryConfig.ThumbnailWidth,
                    ThumbnailPrefix = ProductCategoryConfig.ThumbnailPrefix
                };
                if (!uploadHelper.Save())
                {
                    throw new Exception(uploadHelper.ErrorMessage);
                }
                fileName = uploadHelper.FileName;
                thumFileName = uploadHelper.ThumbnailFileName;
            }
            var strSql = new StringBuilder();
            strSql.Append("update tbproductcategory set ");
            strSql.Append(" CoName=@CoName,");
            strSql.Append(" CoNameEn=@CoNameEn,");
            strSql.Append(" CoSort=@CoSort, ");
            strSql.Append(" CoNormalImage=@CoNormalImage,");
            strSql.Append(" CoSmallImage=@CoSmallImage,");
            strSql.Append(" CoBigImage=@CoBigImage");
            strSql.AppendFormat(" where coproductcategoryid={0} ", id);
            OleDbParameter[] parameters =
                {
                    new OleDbParameter("@CoName", OleDbType.VarChar, 255),
                    new OleDbParameter("@CoNameEn", OleDbType.VarChar, 255),
                    new OleDbParameter("@CoSort", OleDbType.Integer),
                    new OleDbParameter("@CoNormalImage", OleDbType.VarChar, 255),
                    new OleDbParameter("@CoSmallImage", OleDbType.VarChar, 255),
                    new OleDbParameter("@CoBigImage", OleDbType.VarChar, 255)
                };
            parameters[0].Value = name;
            parameters[1].Value = nameEn;
            parameters[2].Value = sort;
            if (filedata != null)
            {
                parameters[3].Value = fileName;
                parameters[4].Value = thumFileName;
                parameters[5].Value = fileName;
            }
            var path = HttpContext.Current.Server.MapPath(ProductCategoryConfig.RelativePath);
            var ds = DbHelperOleDb.Query("select * from tbproductcategory where coproductcategoryid={0}".FormatWith(id));
            foreach (DataRow item in ds.Tables["ds"].Rows)
            {
                FileHelper.DeleteSub(Path.Combine(path, item["CoNormalImage"].SafeToString()));
                FileHelper.DeleteSub(Path.Combine(path, item["CoSmallImage"].SafeToString()));
                FileHelper.DeleteSub(Path.Combine(path, item["CoBigImage"].SafeToString()));
            }
            var obj = DbHelperOleDb.ExecuteSql(strSql.ToString(), parameters).SafeToInt();
            if (!(obj > 0))
            {
                throw new Exception("记录不存在！");
            }
        }

        public void Delete(int id)
        {
            var syscount = DbHelperOleDb.GetSingle("select count(*) from tbproductcategory  where coproductcategoryid={0} and coissystem=1".FormatWith(id)).SafeToInt();
            if (syscount > 0)
            {
                throw new Exception("系统项不能删除！");
            }
            var childcount = DbHelperOleDb.GetSingle("select count(*) from tbproductcategory  where coparentid={0} ".FormatWith(id)).SafeToInt();
            if (childcount > 0)
            {
                throw new Exception("该分类存在子类，请先删除子类！");
            }
            var count = DbHelperOleDb.GetSingle("select count(*) from tbproduct  where coproductcategoryid={0}".FormatWith(id)).SafeToInt();
            if (count > 0)
            {
                throw new Exception("该分类下存在产品，请先删除产品记录！");
            }
            var path = HttpContext.Current.Server.MapPath(ProductCategoryConfig.RelativePath);
            var ds = DbHelperOleDb.Query("select * from tbproductcategory where coproductcategoryid={0}".FormatWith(id));
            foreach (DataRow item in ds.Tables["ds"].Rows)
            {
                FileHelper.DeleteSub(Path.Combine(path, item["CoNormalImage"].SafeToString()));
                FileHelper.DeleteSub(Path.Combine(path, item["CoSmallImage"].SafeToString()));
                FileHelper.DeleteSub(Path.Combine(path, item["CoBigImage"].SafeToString()));
            }
            var obj = DbHelperOleDb.ExecuteSql("delete from tbproductcategory where coproductcategoryid={0}".FormatWith(id)).SafeToInt();
            if (!(obj > 0))
            {
                throw new Exception("记录不存在！");
            }
        }

    }
}
